package com.congapp.conexion;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.congapp.R;
import com.congapp.hot.Inicio;
import com.congapp.hot.menu.MenuLateral;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.plus.PlusClient;
import com.google.android.gms.plus.model.people.Person;

import java.util.Arrays;
import java.util.List;

public class BotonesSociales extends Fragment implements GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener {

    /*private static final BotonesSociales instance;

    static {
        try {
            instance = new BotonesSociales();
        } catch (Exception e) {
            throw new RuntimeException("error iniciando los botones sociales", e);
        }
    }

    public static BotonesSociales getInstance() {
        return instance;
    }

    private BotonesSociales() {
    }*/

    private static final String TAG = BotonesSociales.class.getSimpleName();
    //FB
    private static final List<String> PERMISSIONS = Arrays.asList("public_profile", "email", "user_birthday");
    private UiLifecycleHelper uiHelper;
    //G+
    private static final int OUR_REQUEST_CODE = 49404;
    private Button botonGoogle;
    private Button botonCerrarGoogle;
    private PlusClient plusClient;
    private boolean autoResolverEnFallo;
    private ConnectionResult connectionResult;

    private Activity actividadPadre;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        actividadPadre = getActivity();
        //FB
        uiHelper = new UiLifecycleHelper(actividadPadre, callback);
        uiHelper.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        actividadPadre = getActivity();
        View view;
        if (actividadPadre instanceof Inicio) {
            view = inflater.inflate(R.layout.botones_sociales_inicio, container, false);
        } else {
            view = inflater.inflate(R.layout.botones_sociales, container, false);
        }
        //FB
        LoginButton botonFacebook = (LoginButton) view.findViewById(R.id.botonFacebook);
        botonFacebook.setReadPermissions(PERMISSIONS);
        botonFacebook.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
            @Override
            public void onUserInfoFetched(GraphUser usuario) {
                if (usuario != null) {
                    Log.d("Usuario: ",
                            "Id: " + usuario.getId() +
                                    "\nNombre: " + usuario.getName() +
                                    "\nPrimer nombre: " + usuario.getFirstName() +
                                    "\nSegundo nombre: " + usuario.getMiddleName() +
                                    "\nApellidos: " + usuario.getLastName() +
                                    "\nFecha nacimiento: " + usuario.getBirthday() +
                                    "\nEmail: " + usuario.getProperty("email") +
                                    "\nGenero: " + usuario.getProperty("gender")
                    );
                    iniciarActividad();
                }
            }
        });
        //G+
        plusClient = new PlusClient.Builder(actividadPadre, this, this).setScopes(Scopes.PROFILE, Scopes.PLUS_LOGIN, Scopes.PLUS_ME).build();
        botonGoogle = (Button) view.findViewById(R.id.botonGooglePlus);
        botonGoogle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                signIn();
            }
        });
        botonCerrarGoogle = (Button) view.findViewById(R.id.botonCerrarGooglePlus);
        botonCerrarGoogle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                signOut();
            }
        });
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //FB
        if(uiHelper != null) {
            uiHelper.onActivityResult(requestCode, resultCode, data);
        }
        //G+
        if (requestCode == OUR_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            autoResolverEnFallo = true;
            initiatePlusClientConnect();
        } else if (requestCode == OUR_REQUEST_CODE && resultCode != Activity.RESULT_OK) {

        }
    }

    //FB
    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            if (state.isOpened()) {
                Log.i(TAG, "Facebook login");
            } else if (state.isClosed()) {
                Log.i(TAG, "Facebook logout");
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        uiHelper.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);
    }

    //G+
    @Override
    public void onStart() {
        super.onStart();
        initiatePlusClientConnect();
    }

    @Override
    public void onStop() {
        super.onStop();
        initiatePlusClientDisconnect();
    }

    @Override
    public void onConnected(Bundle bundle) {
        initiatePlusClientConnect();
    }

    @Override
    public void onDisconnected() {
        initiatePlusClientDisconnect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        if (result.hasResolution()) {
            connectionResult = result;
            if (autoResolverEnFallo) {
                startResolution();
            }
        }
    }

    public void signIn() {
        if (!plusClient.isConnected()) {
            autoResolverEnFallo = true;
            if (connectionResult != null) {
                startResolution();
            } else {
                initiatePlusClientConnect();
            }
        }

    }

    public void signOut() {
        if (plusClient.isConnected()) {
            plusClient.clearDefaultAccount();
            initiatePlusClientDisconnect();
        }
    }

    public void revokeAccess() {
        if (plusClient.isConnected()) {
            plusClient.clearDefaultAccount();
            initiatePlusClientDisconnect();
            plusClient.revokeAccessAndDisconnect(new PlusClient.OnAccessRevokedListener() {
                public void onAccessRevoked(ConnectionResult result) {
                    actualizarEstado();
                }
            });
        }
    }

    protected void actualizarEstado() {

        boolean connected = plusClient.isConnected();

        botonCerrarGoogle.setVisibility(connected ? View.VISIBLE : View.GONE);
        botonGoogle.setVisibility(connected ? View.GONE : View.VISIBLE);

        if (connected) {
            Person usuario = plusClient.getCurrentPerson();
            if (usuario != null) {
                Log.d("", "Id: " + usuario.getId() +
                        "\nDisplay Nombre: " + usuario.getDisplayName() +
                        "\nNombre: " + usuario.getName() +
                        "\nFecha nacimiento: " + usuario.getBirthday() +
                        "\nEmail: " + plusClient.getAccountName() +
                        "\nGenero: " + usuario.getGender() +
                        "");
                iniciarActividad();
            }
        }
    }

    private void initiatePlusClientConnect() {
        if (!plusClient.isConnected() && !plusClient.isConnecting()) {
            plusClient.connect();
        }
        Log.i(TAG, "Google plus login");
        actualizarEstado();
    }

    private void initiatePlusClientDisconnect() {
        if (plusClient.isConnected()) {
            plusClient.disconnect();
        }
        Log.i(TAG, "Google plus logout");
        actualizarEstado();
    }

    private void startResolution() {
        try {
            autoResolverEnFallo = false;
            connectionResult.startResolutionForResult(actividadPadre, OUR_REQUEST_CODE);
        } catch (IntentSender.SendIntentException e) {
            connectionResult = null;
            initiatePlusClientConnect();
        }
    }

    private void iniciarActividad() {
        if (actividadPadre instanceof Inicio) {
            startActivity(new Intent(actividadPadre, MenuLateral.class));
        }
    }
}